import 'package:xvideos/tools_base/debug_log.dart';

import '../hj_model/splash/watch_count_model.dart';
import '../hj_model/video_model.dart';
import '../tools_base/global_store/store.dart';
import 'api_service/vid_service.dart';
import 'light_model.dart';

class FreePlayCountManager {
  static final FreePlayCountManager _instance = FreePlayCountManager._();
  factory FreePlayCountManager() => _instance;
  FreePlayCountManager._();

  /// 播放次数
  WatchCount? playCount;

  /// 缓存的播放记录
  final playHistorys = <String>[];
  initConfig() async {
    /// 获取账户免费次数
    playCount = await VidService.fetchVideoWatchCount();
    final temp = (await lightKV.getStringList('new_free_watch_videos')) ?? <String>[];
    playHistorys.addAll(temp);
  }

  clearUserFreePlayCaches() async {
    playCount = null;
    playHistorys.clear();
    await lightKV.setStringList("new_free_watch_videos", playHistorys);
    initConfig();
  }

  bool canFreePlay(VideoModel? videoModel) {
    if (videoModel?.id?.isEmpty ?? true) return false;
    if (videoModel?.freeArea == true || videoModel?.isCoinVideo() == true) return false;
    if (globalStore.isVIP()) return false;
    if (playCount == null) return false;
    if (playHistorys.contains(videoModel?.id)) return true;

    if ((playCount?.watchCount ?? 0) <= 0) {
      //因为先计算后显示, 0要显示1, 服务器那边没有次数了返回的是0,这里需要继续往下减
      playCount?.watchCount = (playCount?.watchCount ?? 0) - 1;
      return false;
    } else {
      playHistorys.add(videoModel?.id ?? '');
      playCount!.watchCount = playCount!.watchCount! - 1;
      try {
        VidService.fetchVideoWatchCount(vid: videoModel?.subid ?? videoModel?.id).then((value) {
          if (value != null) {
            lightKV.setStringList("new_free_watch_videos", playHistorys);
          }
        });
        return true;
      } catch (e) {
        debugLog(e);
        return false;
      }
    }
  }
}
